﻿using Microsoft.Extensions.Caching.Distributed;
using System.Collections.Generic;
namespace Sx.Utils
{
    public static class CacheHelper
    {

        private static readonly IDistributedCache _cache = new NullDistributedCache(); 

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T Get<T>(string key)
        {
            return JsonHelper.ToObject<T>(GetString(key));
        }
        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetString(string key)
        {
            return Cache.GetString(key);
        }
        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void Set<T>(string key, T value)
        {
            SetString(key, JsonHelper.ToJson(value));
        }
        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="opt"></param>
        public static void Set<T>(string key, T value, DistributedCacheEntryOptions opt) {
            SetString(key, JsonHelper.ToJson(value), opt);
        }
        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void SetString(string key, string value)
        {
           SetString(key, value, new DistributedCacheEntryOptions());
        }
        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="opt"></param>
        public static void SetString(string key,string value, DistributedCacheEntryOptions opt) {
            Cache.SetString(key, value, opt);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="key"></param>
        public static void Remove(string key) {
            Cache.Remove(key);
        }

        private static IDistributedCache Cache {
            get {
                var cache = SxHttpContext.GetService<IDistributedCache>();
                if (cache == null)
                {
                    return _cache;
                }
                return cache;
            }
        }
    }

    public interface ICache {
        bool TryGet<T>(string key, out T data);
        T Get<T>(string key);
        bool Save<T>(string key,T data);
    }
}
